package com.eesujie.xcs.util;

import com.eesujie.xcs.common.BusinessException;
import io.minio.*;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Component
@Slf4j
@ConfigurationProperties(prefix = "minio")
public class MinioUtils {
    private MinioClient client;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @PostConstruct
    public void init() {
        client = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }


    public String upload(String bucketName, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String objectName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), 0)
                    .contentType(file.getContentType())
                    .build();
            client.putObject(putObjectArgs);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException("上传图片失败");
        }

        return endpoint + "/" + bucketName + "/" + objectName;
    }

    public void delete(String bucketName, String imageURL) {
        var objectName = imageURL.substring(endpoint.length() + bucketName.length() + 2);
        var args = RemoveObjectArgs.builder().bucket(bucketName)
                .object(objectName)
                .build();

        try {
            client.removeObject(args);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException("删除图片失败");
        }
    }
}
